package com.eurasia.assignment.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ResponseStatusException;

import com.eurasia.assignment.controller.dto.ClassResponse;
import com.eurasia.assignment.controller.dto.ClassSearchRequest;
import com.eurasia.assignment.controller.dto.CreateClassRequest;
import com.eurasia.assignment.controller.dto.PageResponse;
import com.eurasia.assignment.controller.dto.UpdateClassRequest;
import com.eurasia.assignment.domain.Class;
import com.eurasia.assignment.service.ClassService;

/**
 * 班级控制器
 */
@RestController
@RequestMapping("/classes")
public class ClassController {

    private static final Logger log = LoggerFactory.getLogger(ClassController.class);

    private final ClassService classService;

    public ClassController(ClassService classService) {
        this.classService = classService;
    }

    @PostMapping("")
    public ResponseEntity<ClassResponse> createClass(@RequestBody CreateClassRequest request) {
        
        Class createdClass = classService.createClass(request);
        return ResponseEntity.ok(ClassResponse.fromDomain(createdClass));
    }

    /**
     * 获取班级列表（支持分页和条件查询）
     * @param className 班级名称（模糊查询）
     * @param grade 年级（精确查询）
     * @param major 专业（精确查询）
     * @param tutor 辅导员（模糊查询）
     * @param page 页码（从0开始）
     * @param size 每页大小
     * @param sortBy 排序字段
     * @param sortDirection 排序方向（asc/desc）
     * @return 班级分页列表
     */
    @GetMapping
    public ResponseEntity<PageResponse<ClassResponse>> searchClasses(
            @RequestParam(required = false) String className,
            @RequestParam(required = false) String grade,
            @RequestParam(required = false) String major,
            @RequestParam(required = false) String tutor,
            @RequestParam(required = false, defaultValue = "0") Integer page,
            @RequestParam(required = false, defaultValue = "10") Integer size,
            @RequestParam(required = false) String sortBy,
            @RequestParam(required = false, defaultValue = "asc") String sortDirection) {
        
        // 记录接收到的参数
        log.debug("接收到查询请求: className={}, grade={}, major={}, tutor={}, page={}, size={}",
                className, grade, major, tutor, page, size);
        
        // 构建查询请求
        ClassSearchRequest searchRequest = new ClassSearchRequest();
        searchRequest.setClassName(className);
        searchRequest.setGrade(grade);
        searchRequest.setMajor(major);
        searchRequest.setTutor(tutor);
        searchRequest.setPage(page);
        searchRequest.setSize(size);
        searchRequest.setSortBy(sortBy);
        searchRequest.setSortDirection(sortDirection);
        
        // 执行分页查询
        Page<ClassResponse> classResponsePage = classService.searchClasses(searchRequest)
                .map(ClassResponse::fromDomain);
        
        log.debug("查询结果: 总条数={}, 总页数={}, 当前页记录数={}",
                classResponsePage.getTotalElements(),
                classResponsePage.getTotalPages(),
                classResponsePage.getNumberOfElements());
        
        // 构建分页响应
        return ResponseEntity.ok(PageResponse.from(classResponsePage));
    }

    /**
     * 根据ID获取班级信息
     */
    @GetMapping("/{id}")
    public ResponseEntity<ClassResponse> getClassById(@PathVariable Long id) {
        return classService.getClassById(id)
                .map(ClassResponse::fromDomain)
                .map(ResponseEntity::ok)
                .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "班级不存在，ID: " + id));
    }

    /**
     * 更新班级信息
     * @param id 班级ID
     * @param request 更新请求
     * @return 更新后的班级信息
     */
    @PutMapping("/{id}")
    public ResponseEntity<ClassResponse> updateClass(
            @PathVariable Long id,
            @RequestBody UpdateClassRequest request) {
        try {
            Class updatedClass = classService.updateClass(id, request);
            return ResponseEntity.ok(ClassResponse.fromDomain(updatedClass));
        } catch (IllegalArgumentException e) {
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST, e.getMessage());
        } catch (RuntimeException e) {
            throw new ResponseStatusException(HttpStatus.NOT_FOUND, e.getMessage());
        }
    }
}
